/**
 * Created by admin on 2017/12/13.
 */

define([
    "helpers/network",
    "models/roles",
    "views/modules/popup",
    "views/modules/form",
    "views/modules/table",
    "views/modules/pager"
], function (Network, ModelRoles, PopupView, CommonForm, CommonTable, CommonPager) {

    var id = "";
    var windowsId = id + "window";
    var keywordsId = id + "keywordsId";
    var queryPrerequisiteId = id + "queryPrerequisiteId";
    var searchFormId = id + "searchForm";
    var formId = id + "form";
    var tableId = id + "table";
    var pagerId = id + "pager";
    var totalCountsId = id + "totalCounts";
    var rejectWindowId = id + "rejectWindowId";
    var pageNo = 1;
    var updateUrl = '/jobSetting/update.do',
        createUrl = '/jobSetting/create.do',
        deleteUrl = '/jobSetting/delete.do',
        runAtOnceUrl = '/jobSetting/runAtOnce.do',
        canCloseSchedulerUrl = '/jobSetting/canCloseScheduler.do',
        stopAllUrl ='/jobSetting/stopAll.do',
        startAllUrl = '/jobSetting/startAll.do',
        pageQueryUrl = "/jobSetting/queryAll.do";//分页查询数据列表url
    var pageIndex = 1;

    var onTableReady = function (page) {
        var obj = {
            params: {

            },
            size :20,
            page: page || 1,
            sort: ["jobName,asc"]
        };
        Network.ajaxJob(pageQueryUrl, obj, function (ret) {
            pageNo = ret.data.number;
            $$(tableId).clearAll();
            $$(tableId).parse(ret.data.content);
            CommonPager.refreshPager(page, ret.data.totalPages);
            $$(totalCountsId).setValue(ret.data.totalElements + "条数据, 共" + ret.data.totalPages + "页");
        });
        pageIndex = page ? page : 1
    };

//删除系统消息
    var deleteMessage = function () {
        var ooo = $$("table");
        //获取选中元素
        var item = ooo.getSelectedItem();
        if (item) {
            var obj = {
                data: {
                    id: item.id
                }
            }
            Network.ajaxJob(deleteUrl, obj, function (data) {
                ooo.remove(item.id);
                webix.message("删除成功")
            })
        }
    }
    //立即执行一次任务
    var runAtOnce = function () {
        var ooo = $$("table");
        //获取选中元素
        var item = ooo.getSelectedItem();
        if (item) {
            var obj = {
                data: {
                    id: item.id
                }
            }
            Network.ajaxJob(runAtOnceUrl, obj, function (data) {
                webix.message("操作成功");
            })
        }
    }

    var stopAll = function () {
        Network.ajaxJob(stopAllUrl, {}, function (data) {
            webix.message({type:'default ',text:"停止中...",expire:1000});
        });

        var refresh = function() {
            Network.ajaxJob(canCloseSchedulerUrl, {}, function (data) {
                if (data.data) {
                    webix.message({type: 'default ', text: "已全部停止，可以重启定时器系统", expire: 10000});
                    onTableReady();
                } else {
                    webix.message({type: 'default ', text: "停止中...", expire: 1000});
                    setTimeout(function(){refresh()},1000);
                }
            });
        };
        refresh();
    };

    var startAll = function () {
        Network.ajaxJob(startAllUrl, {}, function (data) {
            if(data.message){
                webix.message({type:'default ',text:data.message,expire:3000});
                return;
            }
            webix.message({type:'default ',text:"已全部开启",expire:5000});
            onTableReady();
        });
    }
    var update = function (item) {
        console.log(item)
        var obj = {
            data: item
        };
        if (!$$(formId).validate()) {
            console.log(formId);
            webix.message({type: "warn", text: "您还有未填写的必要数据"});
            return;
        }
        Network.ajaxJob(updateUrl, obj, function (ret) {
            closeWindow();
            webix.message("操作成功！")
            onTableReady(1);

        })
    };
    var closeWindow = function () {
        if ($$(windowsId)) {
            $$(windowsId).close();
        }
        if ($$(rejectWindowId)) {
            $$(rejectWindowId).close();
        }
    };
    var showWindow = function (title, item) {
        console.log(item)
        item = item || {data: {}};
        PopupView(windowsId, title, {
            rows: [
                {
                    cols: [
                        {
                            view: "scrollview", scroll: "y", gravity: 0.4, padding: 0,
                            body: {
                                view: "form", borderless: true, id: formId,
                                elements: [
                                    {name:"id",view: "text", value: item.id,hidden:true}
                                    ,{name:"cron",view: "text", value: item.cron,label: "时间表达式", required: true,labelWidth:100}
                                    ,{name:"jobClassName",view: "text", placeholder:"任务类的全类路径名称",value: item.jobClassName,label: "任务类名", required: true}
                                    ,{ name:"jobName",view: "text",value: item.jobName, label: "任务名称",required: true }
                                    ,{name:"parallelNum", view: "text",placeholder:"默认并发数20", value: item.parallelNum, label: "并发数"}
                                    ,{name:"params", view: "text", value: JSON.stringify(item.params),placeholder:"json数据格式，kv对，如：{k1:v1,k2:v2..}", label: "外部参数"}
                                    ,{name:"switchFlag", view: "select", value: item.switchFlag, label: "开关", required: true ,options: [{id: "Open", value: "开启"},{id: "Close", value: "关闭"}]}
                                    ,{name:"idleDelayTime", view: "text",placeholder:"未抓取到数据时任务下次执行延迟时长，连续多次未抓取，时长累加1倍，最大10倍，默认时长10000毫秒", value: item.idleDelayTime, label: "空闲延迟时间" ,labelWidth:100}
                                ]
                            }
                        }
                    ]
                },
                {
                    padding: 5,
                    cols: [{}, {
                        view: "button", label: "确定", width: 90,
                        click: function () {
                            if (!$$(formId).validate()) {
                                webix.message("信息填写有误, 请仔细录入...");
                                return
                            }
                            var itemValues = $$(formId).getValues();
                            update(itemValues);
                        }
                    },
                    ]
                }
            ]
        }, 500, 500, function () {

        }, closeWindow);
    };


    var genOperationFormUI = function () {
        return {
            view: "scrollview", scroll: "x",
            body: {
                view: "form", css: "toolbar", paddingY: 5, paddingX: 10,
                cols: [
                    {
                        view: "label", label: "操作"
                    },
                    {
                        view: "button", label: "添加", width: 90,
                        hidden: true,
                        click: function () {

                        }
                    },
                    {
                        view: "button", label: "修改", width: 90,
                        // hidden: Authority.hasNoAuth("SYS_MGMT_JOB_MODIFY"),
                        click: function () {
                            if ($$("table").getSelectedItem()) {
                                showWindow("设置", $$("table").getSelectedItem())
                            }
                        }
                    },
                    {
                        view: "button", label: "删除", width: 90, type: "danger",
                        hidden: true,
                        click: deleteMessage
                    },
                    {
                        view: "button", label: "执行一次", width: 90,
                        // hidden: Authority.hasNoAuth("SYS_MGMT_JOB_EXECUTE"),
                        type: "base", click: runAtOnce
                    },
                    {
                        view: "button", label: "全部停止", width: 90,
                        hidden:false,
                        type: "base", click: stopAll
                    },
                    {
                        view: "button", label: "全部开始", width: 90,
                        hidden: false,
                        type: "base", click: startAll
                    },
                    {
                        view: "button", label: "刷新", width: 90,
                        type: "base", click: function(){onTableReady(pageNo);}
                    }
                ]
            }
        }
    };

    var genDataTableUI = function () {
        return {
            id: tableId, view: "datatable", resizeColumn: true, select: "row",
            data:[],
            complexData: true,
            ready:onTableReady,
            columns: [
                {id: "id", header: "ID", width: 100},
                {id: "cron", header: "时间表达式",width: 150},
                // {id: "jobClassName", header: "任务全类路径名",width:450},
                {id: "jobName", header: "任务名",width: 200},
                {id: "vJobStatusText", header: "任务状态",template:function(obj){
                    if(obj.switchFlag == 'Close' )return '';
                    else if(obj.switchFlag == 'Open' && !obj.vJobStatusText) return '空闲';
                    else return obj.vJobStatusText;
                }},
                {id: "curMinuteSuccessNum", header: "当前分钟成功数",width: 120},
                {id: "curMinuteFailNum", header: "当前分钟失败数",width: 120},
                {id: "preMinuteSuccessNum", header: "上分钟成功数",width: 120},
                {id: "preMinuteFailNum", header: "上分钟失败数",width: 120},
                {id: "curPeriodSuccessNum", header: "本次运行成功数",width: 120,template:function(obj){
                    return obj.curPeriodSuccessNum+obj.curMinuteSuccessNum;
                }},

                {id: "curPeriodFailNum", header: "本次运行失败数",width: 120,template:function(obj){
                    return obj.curPeriodFailNum+obj.curMinuteFailNum;
                }},
                {id: "totalSuccessNum", header: "累计成功数",width: 120,template:function(obj){
                    return obj.totalSuccessNum+obj.curMinuteSuccessNum;
                }},
                {id: "totalFailNum", header: "累计失败数",width: 120,template:function(obj){
                    return obj.totalFailNum+obj.curMinuteFailNum;
                }},
                {id: "vSwitchFlagText", header: "任务开关"},
                {id: "idleDelayTime", header: "空闲超时时间"}
            ]
        }
    };

    var genFooterUI = function () {
        return {
            cols: [
                CommonPager.genPagerUI(pagerId, onTableReady),
                CommonPager.genTotalCountsUI(totalCountsId), {}
            ]
        }
    };

    return {
        $ui: {
            padding: 10,
            rows: [
                genOperationFormUI(),
                genDataTableUI(),
                genFooterUI()
            ]
        }
    };

});